<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="证件号码" prop="idNumber">
        <el-input
          v-model="queryParams.idNumber"
          placeholder="请输入证件号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐名称" prop="planName">
        <el-select v-model="queryParams.planName" placeholder="请选择套餐名称" clearable>
          <el-option
            v-for="item in planList"
            :key="item.planId"
            :label="item.planName"
            :value="item.planName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="套餐价格" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入套餐价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账单地址" prop="billingAddress">
        <el-input
          v-model="queryParams.billingAddress"
          placeholder="请输入账单地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电子邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入电子邮箱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开户时间" prop="registrationDate">
        <el-date-picker clearable
          v-model="queryParams.registrationDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开户时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:account:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:account:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:account:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:account:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="accountList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="开户ID" align="center" prop="accountId" />
      <el-table-column label="客户姓名" align="center" prop="name" />
      <el-table-column label="证件类型" align="center" prop="idType" />
      <el-table-column label="证件号码" align="center" prop="idNumber" />
      <el-table-column label="手机号码" align="center" prop="phoneNumber" />
      <el-table-column label="卡类型" align="center" prop="cardType" />
      <el-table-column label="套餐名称" align="center" prop="planName" />
      <el-table-column label="套餐价格" align="center" prop="price" />
      <el-table-column label="账户余额" align="center" prop="balance" />
      <el-table-column label="账单地址" align="center" prop="billingAddress" />
      <el-table-column label="电子邮箱" align="center" prop="email" />
      <el-table-column label="开户时间" align="center" prop="registrationDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.registrationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账户状态" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:account:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:account:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改通讯人员开户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="证件类型" prop="idType">
          <el-select v-model="form.idType" placeholder="请选择证件类型" @change="handleIdTypeChange">
            <el-option label="身份证" value="身份证" />
            <el-option label="护照" value="护照" />
            <el-option label="港澳通行证" value="港澳通行证" />
            <el-option label="台胞证" value="台胞证" />
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码" prop="idNumber">
          <el-input v-model="form.idNumber" placeholder="请输入证件号码" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号码" readonly>
            <el-button slot="append" @click="showPhoneNumberDrawer = true">选择号码</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="套餐名称" prop="planName">
          <el-select v-model="form.planName" placeholder="请选择套餐名称" @change="handlePlanChange">
            <el-option
              v-for="item in planList"
              :key="item.planId"
              :label="item.planName" 
              :value="item.planName">
            </el-option>
          </el-select>
          <el-button type="text" @click="showPlanDetail = true">查看套餐详情</el-button>
        </el-form-item>
        <el-form-item label="套餐价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入套餐价格" />
        </el-form-item>
        <el-form-item label="充值金额" prop="rechargeAmount">
          <el-input v-model="form.rechargeAmount" placeholder="请输入充值金额" />
        </el-form-item>
        <el-form-item label="账单地址" prop="billingAddress">
          <el-input v-model="form.billingAddress" placeholder="请输入账单地址" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <el-form-item label="开户时间" prop="registrationDate">
          <el-date-picker clearable
            v-model="form.registrationDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择开户时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 套餐详情侧边栏 -->
    <el-drawer
      title="套餐详情"
      :visible.sync="showPlanDetail"
      direction="rtl"
      size="30%"
      :modal="true"
      :with-header="true"
      custom-class="plan-detail-drawer">
      <div v-if="selectedPlan" class="plan-detail-content">
        <el-card shadow="never" class="plan-card">
          <div class="detail-item">
            <span class="label">套餐名称</span>
            <span class="value">{{ selectedPlan.planName }}</span>
          </div>
          <el-divider></el-divider>
          <div class="detail-item">
            <span class="label">套餐价格</span>
            <span class="value price">¥{{ selectedPlan.price }}<small>/月</small></span>
          </div>
          <el-divider></el-divider>
          <div class="detail-item">
            <span class="label">套餐描述</span>
            <p class="description">{{ selectedPlan.description }}</p>
          </div>
        </el-card>
      </div>
    </el-drawer>

    <!-- 手机号码选择侧边栏 -->
    <el-drawer
      title="选择手机号码"
      :visible.sync="showPhoneNumberDrawer"
      direction="rtl"
      size="30%">
      <div class="phone-number-list">
        <el-radio-group v-model="form.phoneNumber" class="phone-radio-group">
          <el-radio 
            v-for="number in phoneNumbers" 
            :key="number"
            :label="number"
            class="phone-radio-item">
            {{ number }}
          </el-radio>
        </el-radio-group>
        <div class="drawer-footer">
          <el-button type="primary" @click="generateNewNumbers">重新生成号码</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listAccount, getAccount, delAccount, addAccount, updateAccount,generateAccessNumber } from "@/api/personal/account";
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/plan/plan";

export default {
  name: "Account",
  data() {
    // 身份证号码验证规则
    const validateIdCard = (rule, value, callback) => {
      const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (this.form.idType === '身份证' && !reg.test(value)) {
        callback(new Error('请输入正确的身份证号码'));
      } else {
        callback();
      }
    };
    // 护照号码验证规则
    const validatePassport = (rule, value, callback) => {
      const reg = /^[a-zA-Z]\d{8}$/;
      if (this.form.idType === '护照' && !reg.test(value)) {
        callback(new Error('请输入正确的护照号码'));
      } else {
        callback();
      }
    };
    // 港澳通行证验证规则
    const validateHKMacao = (rule, value, callback) => {
      const reg = /^[HMhm]{1}([0-9]{10}|[0-9]{8})$/;
      if (this.form.idType === '港澳通行证' && !reg.test(value)) {
        callback(new Error('请输入正确的港澳通行证号码'));
      } else {
        callback();
      }
    };
    // 台胞证验证规则
    const validateTaiwan = (rule, value, callback) => {
      const reg = /^([0-9]{8}|[0-9]{10})$/;
      if (this.form.idType === '台胞证' && !reg.test(value)) {
        callback(new Error('请输入正确的台胞证号码'));
      } else {
        callback();
      }
    };

    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 通讯人员开户表格数据
      accountList: [],
      // 套餐列表数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示套餐详情
      showPlanDetail: false,
      // 是否显示手机号码选择
      showPhoneNumberDrawer: false,
      // 可选手机号码列表
      phoneNumbers: [],
      // 选中的套餐
      selectedPlan: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        idType: null,
        idNumber: null,
        phoneNumber: null,
        cardType: null,
        planName: null,
        price: null,
        billingAddress: null,
        email: null,
        registrationDate: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "客户姓名不能为空", trigger: "blur" }
        ],
        idType: [
          { required: true, message: "证件类型不能为空", trigger: "change" }
        ],
        idNumber: [
          { required: true, message: "证件号码不能为空", trigger: "blur" },
          { validator: validateIdCard, trigger: 'blur' },
          { validator: validatePassport, trigger: 'blur' },
          { validator: validateHKMacao, trigger: 'blur' },
          { validator: validateTaiwan, trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: "手机号码不能为空", trigger: "blur" }
        ],
        cardType: [
          { required: true, message: "卡类型不能为空", trigger: "change" }
        ],
        planName: [
          { required: true, message: "套餐名称不能为空", trigger: "blur" }
        ],
        rechargeAmount: [
          { required: true, message: "充值金额不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getPlanList();
  },
  methods: {
    /** 查询通讯人员开户列表 */
    getList() {
      this.loading = true;
      listAccount(this.queryParams).then(response => {
        this.accountList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询套餐列表 */
    getPlanList() {
      listPlan().then(response => {
        this.planList = response.rows;
      });
    },
    /** 生成新的手机号码列表 */
    generateNewNumbers() {
      generateAccessNumber().then(response => {
        if(response.code === 200) {
          this.phoneNumbers = response.data;
        }
      });
    },
    /** 套餐选择变更 */
    handlePlanChange(planName) {
      const plan = this.planList.find(p => p.planName === planName);
      if (plan) {
        this.selectedPlan = plan;
        this.form.price = plan.price;
      }
    },
    /** 证件类型变更时清空证件号码 */
    handleIdTypeChange() {
      this.form.idNumber = '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        accountId: null,
        name: null,
        idType: null,
        idNumber: null,
        phoneNumber: null,
        cardType: null,
        planName: null,
        price: null,
        rechargeAmount: null,
        billingAddress: null,
        email: null,
        registrationDate: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.accountId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加通讯人员开户";
      this.generateNewNumbers();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const accountId = row.accountId || this.ids
      getAccount(accountId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改通讯人员开户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.accountId != null) {
            updateAccount(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAccount(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const accountIds = row.accountId || this.ids;
      this.$modal.confirm('是否确认删除通讯人员开户编号为"' + accountIds + '"的数据项？').then(function() {
        return delAccount(accountIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/account/export', {
        ...this.queryParams
      }, `account_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.plan-detail-content {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-item label {
  font-weight: bold;
  color: #606266;
  margin-right: 8px;
}

.detail-item p {
  margin: 8px 0;
  color: #606266;
  line-height: 1.5;
}

.detail-item ul {
  margin: 8px 0;
  padding-left: 20px;
}

.detail-item li {
  color: #606266;
  line-height: 1.8;
}

.phone-number-list {
  padding: 20px;
  height: 100%;
  position: relative;
}

.phone-radio-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 60px;
}

.phone-radio-item {
  background: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  width: 100%;
  margin: 0;
  transition: all 0.3s;
}

.phone-radio-item:hover {
  background: #e6f1fc;
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  text-align: center;
  background: #fff;
  border-top: 1px solid #e4e7ed;
}
</style>
